import { isRef, isReactive, toRaw } from 'vue';
import screenfull from 'screenfull';
import { message } from 'ant-design-vue';
import aMapError from '@/network/error/aMapError';
export const getUrlKey = (name) => {
  return (
    decodeURIComponent(
      (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
        location.href
      ) || [''])[1]?.replace(/\+/g, '%20')
    ) || null
  );
};
//对象转数组
export const aimToArr = (Data) => {
  let arr = [];
  Object.keys(Data).map((key) => {
    let obj = {
      label: Data[key],
      value: key,
    };
    arr.push(obj);
  });
  return arr;
};
//to JSON string
/**
 *
 * @param {*} list
 */
export const toStringify = (list) => {
  if (list) {
    list.forEach((item) => {
      item.componentsList
        ? item.componentsList.forEach((componentsListItem) => {
            componentsListItem.closeValve = componentsListItem.closeValve
              ? JSON.stringify(componentsListItem.closeValve)
              : '';
            componentsListItem.openValve = componentsListItem.openValve
              ? JSON.stringify(componentsListItem.openValve)
              : '';
          })
        : '';
      item.groupLists ? toStringify(item.groupLists) : '';
    });
  }
};
export const toParse = (list) => {
  if (list) {
    list.forEach((item) => {
      item.componentsList
        ? item.componentsList.forEach((componentsListItem) => {
            componentsListItem.closeValve = componentsListItem.closeValve
              ? JSON.parse(componentsListItem.closeValve)
              : '';
            componentsListItem.openValve = componentsListItem.openValve
              ? JSON.parse(componentsListItem.openValve)
              : '';
          })
        : '';
      item.groupLists ? toParse(item.groupLists) : '';
    });
  }
};
export const imageUrlToBase64 = (networkUrl) => {
  return new Promise((resolve) => {
    //一定要设置为let，不然图片不显示
    let image = new Image();
    //解决跨域问题
    image.setAttribute('crossOrigin', 'anonymous');
    let imageUrl = networkUrl;
    image.src = imageUrl;
    //image.onload为异步加载
    image.onload = () => {
      var canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      var context = canvas.getContext('2d');
      context.drawImage(image, 0, 0, image.width, image.height);
      var quality = 0.8;
      resolve(canvas.toDataURL('image/jpeg', quality)); //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
    };
  });
};

export const DeepClone = (data) => {
  if (isRef(data) || isReactive(data)) {
    data = toRaw(data);
  }
  let newData = null;
  if (data && typeof data === 'object') {
    newData = data instanceof Array ? [] : {};
    for (let i in data) {
      newData[i] = typeof i === 'object' ? this.DeepClone(data[i]) : data[i];
    }
  } else {
    newData = data;
  }
  return newData;
};

/**
 *
 * @param {*} ele 文本节点
 * @returns
 */
export const fullScreen = (ele) => {
  return new Promise((resolve, reject) => {
    if (screenfull.isEnabled) {
      if (!screenfull.isFullscreen) {
        // screenfull.toggle(ele);
        screenfull.request(ele);
        resolve({ msg: '进入全屏', status: true });
      } else {
        screenfull.exit();
        resolve({ msg: '退出全屏', status: false });
      }
    } else {
      const msg = '当前浏览器暂不支持全屏哦~';
      message.error(msg);
      reject({ msg, status: false });
    }
  });
};

/**
 *
 * @param {*} x 经度 ||  x 像素坐标
 * @param {*} y 纬度 || x 像素坐标
 * @param {*} map  地图对象
 * @param {*} type 转换类型
 * @returns
 */
export const pixelSwapToLanLat = (x, y, map, type = 'lanLat') => {
  //容器像素转经纬度
  if (type == 'lanLat') {
    return map.containerToLngLat(new AMap.Pixel(x, y));
  } else {
    //经纬度转容器像素
    return map.lngLatToContainer(new AMap.LngLat(x, y));
  }
};
/**
 * 防抖函数
 * @param {*} fn 用户传入需要防抖的函数
 * @param {*} time 等待时间
 * @returns
 */
export const debounce = (fn, time = 1000) => {
  let timer = null;
  return function (...args) {
    let _this = this;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(_this, args);
    }, time);
  };
};

//冒泡排序
export const Insertion = (arr) => {
  for (var i = 0; i < arr.length - 1; i++) {
    for (var j = 0; j < arr.length - i - 1; j++) {
      if (arr[j].val > arr[j + 1].val) {
        var a = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = a;
      }
    }
  }
  return arr;
};

/**
 *二叉树查找法
 * @param {*} arr 可匹配数组范围
 * @param {*} num 当前输入数值
 * @returns
 */
export const binaryTreeFun = (arr, num) => {
  let len = arr.length;
  let leftIndex = 0;
  let rightIndex = len - 1;
  while (leftIndex <= rightIndex) {
    let mid = Math.floor((leftIndex + rightIndex) / 2);
    if (
      num >= arr[mid].val &&
      num < arr[mid + 1 <= arr.length - 1 ? mid + 1 : mid].val
    ) {
      // 找到返回
      return arr[mid];
    } else if (num > arr[mid].val) {
      // 比中间值大，说明在 mid 到 rightIndex 之间；否则就在 mid 到 leftIndex 之间
      leftIndex = mid + 1;
    } else {
      rightIndex = mid - 1;
    }
  }
  if (num >= arr[arr.length - 1].val) {
    return arr[arr.length - 1];
  } else {
    return -1; // 没找到返回-1
  }
};

/**
 * 转换成blob
 * @param {*} dataURI  base64格式
 * @returns
 */
const dataURItoBlob = (dataURI) => {
  //图片转成Buffer
  var byteString = atob(dataURI.split(',')[1]);
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], { type: mimeString });
};
/**
 * 图片上传格式
 * @param {*} src  base64
 * @param {*} name 名称
 * @param {*} type  图片类型
 * @returns
 */
export const convertCanvasToImage = (
  src,
  name = 'templateImg',
  type = 'jpg'
) => {
  let formData = new FormData();
  formData.append('file', dataURItoBlob(src), `${name}.${type}`);
  return formData;
};

/**
 * 关于使用原生获取组件原因:每一层loca创建是默认创建click和mousemove事件，导致浏览器卡顿（后续作者说优化正一块，可废用这个方法）
 * 详情使用方法请查看官网
 * @param {Array} pixel [x,y] 当前鼠标像素 *
 * @param {string} refArr 要查询的ref对象 *
 * @param {Object} _this this对象 *
 */
export const queryMapComponentFeature = (pixel, refArr, _this) => {
  return new Promise((resolve) => {
    //local层的数组；local层
    for (let ref in refArr) {
      const mapComponentsLength = _this.mapComponents.localLayer[ref].length;
      if (mapComponentsLength > 0) {
        //组件层
        _this.mapComponents.localLayer[ref].forEach((mapComponent, index) => {
          const childrenRef = _this.$refs[ref][`get${ref}Ref`](index)[0]; //获取第index个local层ref
          var locaComponent = childrenRef.$$getInstance().queryFeature(pixel);
          locaComponent ? resolve(locaComponent) : '';
        });
      }
    }
  });
};
